#!/usr/bin/python2.5
#
"""Main page for mm2notes."""

__author__ = 'scottkirkwood@google.com (Scott Kirkwood)'

import datetime
import logging
import mm2notes
import os
import re
import schema
import time
import util

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template

import wsgiref.handlers

class DeleteMeeting(webapp.RequestHandler):
    """Handling of the Delete Meeting page."""

    @util.ForceLogin()
    def post(self):
        """Standard POST request."""
        user = users.get_current_user()

        key = self.request.get('key')
        meet = Meeting()
        meet.delete_meeting(key)
        self.redirect('/')

class Meeting:
    def add_meeting(self, user, fname, text):
        mm2n = mm2notes.Mm2Notes()
        mm2n.xmlparse(text)
        info = mm2n.convert()
        meeting = schema.Meeting(user=user, topic='\n'.join(info['topic']))
        meeting.fname = 'fname'  # '\n'.join(fname)
        meeting.emails = info['emails']
        meeting.attendees = info['attendees']
        meeting.mm_source = text
        meeting.put()

        for timestamp, person, notes in info['discussed']:
            t = datetime.datetime.fromtimestamp(timestamp / 1000.0)
            minutes = schema.Minutes(meeting=meeting, timestamp=t,
                    person=person, text=notes)
            minutes.put()

        if user.email() not in info['emails']:
            info['emails'].append(user.email())
            logging.debug('user %s was missing from own meeting' % user.email())
            
        for email in info['emails']:
            e2m = schema.UserToMeeting(email=email.strip(),
                    meeting=meeting, topic=' '.join(info['topic']),
                    attendees=info['attendees'])
            logging.debug('adding %s to %s' % (email, ' '.join(info['topic'])))
            e2m.put()
        return meeting.key()

    def delete_meeting(self, key):
        meeting = schema.Meeting.get(key)
        q = schema.UserToMeeting.gql('WHERE meeting=:1', meeting)
        db.delete(q.fetch(1000))
        logging.info('Deleted UserToMeeting')
        q = schema.Minutes.gql('WHERE meeting=:1', meeting)
        db.delete(q.fetch(1000))
        logging.info('Deleted meeting minutes')
        meeting.delete()
        logging.info('Deleted meeting')
